import React, { useEffect, useState } from 'react';
import { definePageConfig, history, useAuth } from 'ice';
import { message, Button, notification } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import styles from './index.module.css';
import type { LoginParams } from '@/interfaces/user';
import { login, fetchUserInfo } from '@/services/user';
import store from '@/store';
import { ROLE } from '@/common/const'

const Login: React.FC = () => {
  const [, userDispatcher] = store.useModel('user');
  const [, setAuth] = useAuth();
  const [loginParams, setLoginParams] = useState<LoginParams>({
    jobnumber: '',
    password: ''
  })
  const [loading, setLoading] = useState(false);
  async function updateUserInfo() {
    const { data } = await fetchUserInfo();
    setAuth({
      ADMIN: (data.role as string).toUpperCase() === ROLE.ADMIN,
      ZL: data.role === ROLE.ZL,
      YS: data.role === ROLE.YS,
      CKY: data.role === ROLE.CKY,
      RKY: data.role === ROLE.RKY,
    });
    userDispatcher.updateCurrentUser(data);
  }

  async function handleSubmit() {
    if (!loginParams.jobnumber || !loginParams.password) {
      message.error('请输入账号及密码！')
      return
    }
    try {
      setLoading(true)
      const { data, code, message: errorInfo } = await login(loginParams);
      const loginResult = code === 200;
      if (loginResult) {
        sessionStorage.setItem('token', data.token)
        notification.success({
          message: '登录成功',
          duration: 1.5,
        }
        );
        await updateUserInfo();
        history?.push('/');
        return;
      } else {
        message.error(errorInfo);
      }
    } catch (error) {
      message.error('登录失败，请重试！');
      console.log(error);
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => {
    console.log('sessionStorage')
    const token = sessionStorage.getItem('token') || ''
    if (token) history?.push('/patients')
  }, [])

  const changeUser = (e, key) => {
    setLoginParams({
      ...loginParams,
      [key]: e.target.value
    })
  }
  return (
    <div className={styles.container}>
      <form>
        <h3>保定新生医院管理系统</h3>
        <label ><UserOutlined /> 账号</label>
        <input type="text" placeholder="请输入账号..." id="jobnumber" onChange={(e) => changeUser(e, 'jobnumber')} />
        <label ><LockOutlined /> 密码</label>
        <input type="password" placeholder="请输入密码..." id="password" onChange={(e) => changeUser(e, 'password')} onKeyUp={(e) => {
          if (e.keyCode === 13) {
            handleSubmit()
          }
        }} />
        <Button type='primary' block className={styles.btn} onClick={() => handleSubmit()} loading={loading}>登录</Button>
      </form>
    </div>
  );
};

export const pageConfig = definePageConfig(() => {
  return {
    title: '登录',
  };
});

export default Login;
